package cn.ultrarisk.scadmin.manager.biz.user.dao;

import cn.ultrarisk.scadmin.manager.biz.user.entity.Privilege;
import cn.ultrarisk.scadmin.manager.support.BaseDAO;
import cn.ultrarisk.scadmin.manager.util.CollectionUtil;
import org.springframework.stereotype.Repository;

import java.util.*;

/**
 * 权限数据操作类
 *
 * @author sevendlong(lin23871@163.com)
 * @date 2014/3/28
 * @since V1.0
 */
@Repository
public class PrivilegeDAO extends BaseDAO<Privilege, Integer> {
    /**
     * 构造器
     */
    public PrivilegeDAO() {
        super(Privilege.class, Privilege.COLUMN_PROPERTY_MAP);
    }

    /**
     * 装配成对象
     *
     * @query oldPrivileges
     * @return
     */
    public List<Privilege> assembly(List<Privilege> oldPrivileges) {
        List<Privilege> newPrivileges = new ArrayList<Privilege>();
        for (Privilege oldPrivilege : oldPrivileges) {
            if (oldPrivilege.getParentId() == null || oldPrivilege.getParentId() == 0) {
                newPrivileges.add(oldPrivilege);
            }
        }
        for (Privilege newPrivilege : newPrivileges) {
            for (Privilege oldPrivilege : oldPrivileges) {
                if (newPrivilege.getId().equals(oldPrivilege.getParentId())) {
                    newPrivilege.addChild(oldPrivilege);
                }
            }
        }
        return newPrivileges;
    }

    public List<Privilege> findByRoleId(Integer roleId) {
        return findByRoleIds(CollectionUtil.asList(roleId));
    }

    public List<Privilege> findByRoleIds(List<Integer> roleIds) {
        Map<String, Object> query = new HashMap<String, Object>();
        query.put("roleIds", roleIds);
        return sqlSessionTemplate.selectList(entityName + ".listByRoleIds", query);
    }

    public Map<Integer, Integer> getCollectionPrivilegeRoleMap(Collection<Integer> roleIds) {
        Map<String, Object> query = new HashMap<String, Object>();
        query.put("roleIds", roleIds);
        List<Map<String, Integer>> list = sqlSessionTemplate.selectList(entityName + ".listCollectionRoleMap", query);

        Map<Integer, Integer> result = new HashMap<Integer, Integer>();
        for (Map<String, Integer> map : list) {
            Integer roleId = Integer.parseInt(map.get("role_id").toString());
            Integer privilegeId = Integer.parseInt(map.get("privilege_id").toString());
            result.put(privilegeId, roleId);
        }
        return result;
    }
}
